package com.zhuimeng.Application.contorller;


import com.zhuimeng.Application.entity.Room;
import com.zhuimeng.Application.entity.RoomVo;
import com.zhuimeng.Application.entity.message;
import com.zhuimeng.Application.utils.RoomCodeUtils;
import com.zhuimeng.Application.utils.RoomMangerUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/room")
public class RoomController {

    @RequestMapping("/list")
    public List<RoomVo> roomList() {
        List<Room> rooms = RoomMangerUtils.getRoomList();
        List<RoomVo> roomVos = rooms.stream().map(room -> {
            RoomVo roomVo = new RoomVo();
            roomVo.setRid(room.getRoomId());
            roomVo.setNickName(room.getPlayer1().getUser().getNickname());
            roomVo.setInfo(room.getInfo());
            roomVo.setIsPass(StringUtils.isEmpty(room.getPass()) ? 0 : 1);
            roomVo.setStatus(room.getStatus());
            roomVo.setIsSubscrribe(room.getIsSubscrribe());
            return roomVo;
        }).collect(Collectors.toList());
        return roomVos;
    }

    @RequestMapping("/joinRoom")
    public message joinRoom(Integer rid, String pass) {
        synchronized ((rid + "").intern()) {
            Room room = RoomMangerUtils.getRoom(rid);
            if (room == null) {
                return message.returnmessage("300", "房间不存在");
            }
            if (!room.getPass().equals(pass)) {
                return message.returnmessage("302", "密码错误");
            }
            if (room.getStatus() != 0) {
                return message.returnmessage("301", "房间人数已满");
            } else {
                room.setStatus(1);
                String code = Math.floor(Math.random() * 1000) + "";
                RoomCodeUtils.putCode(rid.toString(), code);
                return message.returnmessage("400", "验证成功").add("roomCode", code);
            }
        }
    }
}
